package com.eve.springcloud.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.eve.springcloud.common.Jsons;
import com.eve.springcloud.handler.CustomerBlockHandler;

/**
 * 20200707
 *   限流 @SentinelResource注解
 * @author HXL
 *
 */
@RestController
@RequestMapping("/rate")
public class RateLimieController {
	
	@GetMapping("/byResource")
	@SentinelResource(value = "byResource", blockHandler = "handleException")
	public Jsons byResource() {
		Jsons ok = Jsons.error(200, "按资源名称限流测试OK").put("data", "serial001");
		return ok;
	}
	/**
	 * 设置的自定义限流返回方法
	 * @param exception
	 * @return
	 */
	public Jsons handleException(BlockException exception) {
		Jsons ok = Jsons.error(444, exception.getClass().getCanonicalName()+"\t 服务不可用");
		return ok;
	}
	/**
	 * 按url限流：未设置限流处理方法
	 * @return
	 */
	@GetMapping("/byUrl")
	@SentinelResource(value = "byUrl")
	public Jsons byUrl() {
		Jsons ok = Jsons.error(200, "按URL限流测试OK").put("data", "serial002");
		return ok;
	}
	/**
	 * 自定义限流处理类
	 * 自定义处理类+处理方法
	 * @return
	 */
	@GetMapping("/customerBlockHandler2")
	@SentinelResource(value = "customerBlockHandler", blockHandlerClass = CustomerBlockHandler.class
	, blockHandler = "handlerException2")
	public Jsons customerBlockHandler() {
		Jsons ok = Jsons.error(200, "自定义限流处理类测试OK").put("data", "serial003");
		return ok;
	}
	
	/**
	 * 自定义限流处理类
	 * 自定义处理类+不定义处理方法（返回sentinel默认的处理方法）
	 * @return
	 */
	@GetMapping("/customerBlockHandler1")
	@SentinelResource(value = "customerBlockHandler", blockHandlerClass = CustomerBlockHandler.class
	)
	public Jsons customerBlockHandler1() {
		Jsons ok = Jsons.error(200, "自定义限流处理类测试OK").put("data", "serial004");
		return ok;
	}
}
